package com.ssy.invoicing.order.service;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chapter;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.ssy.invoicing.common.util.DateUtil;
import com.ssy.invoicing.common.util.ExcelUtil;
import com.ssy.invoicing.common.util.PDFUtil;
import com.ssy.invoicing.dao.support.BaseSqlDao.SplitPageResult;
import com.ssy.invoicing.order.bean.PurchaseOrderBean;
import com.ssy.invoicing.order.bean.PurchaseProductBean;
import com.ssy.invoicing.order.bean.vo.OrderVo;
import com.ssy.invoicing.order.dao.PurchaseDao;

@Service(value="purchaseService")
@Transactional
public class PurchaseService {
    
    @Resource(name="purchaseDao")
    private PurchaseDao purchaseDao;

    /**
     * 批量保存采购订单信息
     * @author suoyao.shen
     * @param orderNumber
     * @param saleCount
     * @param salePrice
     * @param totalPrice
     * @param deliverTime
     * @param suppliers
     * @param remark
     * @param purchaseId
     */
    public void savePurchaseBatch(String orderId, String orderNumber, String[] pname, String[] pattern, Integer[] saleCount, String[] salePrice,
                                  String[] totalPrice, Date[] deliverTime, String[] suppliers,
                                  String[] remark, Integer[] purchaseId) {
        //增加采购订单
        PurchaseOrderBean purchase = purchaseDao.savePurchase(new PurchaseOrderBean(Integer.parseInt(orderId),orderNumber,"CG-" + orderNumber));
        //批量增加采购订单的产品信息
        List<PurchaseProductBean> productList = new ArrayList<PurchaseProductBean>();
        for (int i = 0, len = pname.length; i < len; i++) {
            String contractNumber = "";
            if(i <= 9) {
                contractNumber = "00" + (i+1);
            } else if(i <= 99) {
                contractNumber = "0" + (i+1);
            } else {
                contractNumber = String.valueOf(i+1);
            }
            PurchaseProductBean product = new PurchaseProductBean(orderNumber + "-" + contractNumber,pname[i], pattern[i],
                    saleCount[i], salePrice[i], totalPrice[i], deliverTime[i], suppliers[i], remark[i], purchase.getId());
            productList.add(product);
        }
        purchaseDao.savePurchaseProductBatch(productList);
    }
    
    /**
     * @param vo
     * @return
     * @throws SQLException
     */
    public SplitPageResult queryPurchaseList(OrderVo vo) throws SQLException {
        return purchaseDao.queryPurchaseList(vo.initParams(), vo.getPage());
    }
    
    /**
     * 根据采购订单Id获得采购订单信息
     * @param purchaseId
     * @return
     */
    public PurchaseOrderBean getPurchaseById(Integer purchaseId) {
        return purchaseDao.getPurchaseById(purchaseId);
    }
    
    /**
     * 根据采购订单加载产品信息
     * @param purchaseId
     * @return
     */
    public List<PurchaseProductBean> loadProductByPurchaseId(Integer purchaseId) {
        return purchaseDao.loadProductByPurchaseId(purchaseId);
    }
    
    /**
     * @param id
     */
    public void removePurchase(Integer id) {
        purchaseDao.removePurchase(id);
        /*
         * 删除采购订单对应的产品信息
         */
        purchaseDao.removePurchaseProduct(id);
    }
    
    /**
     * 修改采购订单的产品信息
     * @param purchaseId
     * @param pname
     * @param pattern
     * @param saleCount
     * @param salePrice
     * @param totalPrice
     * @param deliverTime
     * @param suppliers
     * @param remark
     */
    public void saveAdditionalPurchase(String orderNumber,Integer purchaseId, String[] pname, String[] pattern,
                                       Integer[] saleCount, String[] salePrice,
                                       String[] totalPrice, Date[] deliverTime,
                                       String[] suppliers, String[] remark) {
        /*
         * 删除采购订单对应的产品信息
         */
        purchaseDao.removePurchaseProduct(purchaseId);
        /*
         * 批量增加采购订单的产品信息
         */
        List<PurchaseProductBean> productList = new ArrayList<PurchaseProductBean>();
        for (int i = 0, len = pname.length; i < len; i++) {
            String contractNumber = "";
            if(i <= 9) {
                contractNumber = "00" + (i+1);
            } else if(i <= 99) {
                contractNumber = "0" + (i+1);
            } else {
                contractNumber = String.valueOf(i+1);
            }
            PurchaseProductBean product = new PurchaseProductBean(orderNumber + "-" + contractNumber,pname[i], pattern[i],
                    saleCount[i], salePrice[i], totalPrice[i], deliverTime[i], suppliers[i], remark[i], purchaseId);
            productList.add(product);
        }
        purchaseDao.savePurchaseProductBatch(productList);
    }
    
    /**
     * 生成pdf文件
     * @param purchaseId
     * @return
     */
    public File generatePDF(Integer purchaseId) throws IOException, DocumentException {
        /*
         * 获取采购订单信息 
         */
        PurchaseOrderBean purchase = purchaseDao.getPurchaseById(purchaseId);
        /*
         * 获取采购订单下面的产品信息
         */
        List<PurchaseProductBean> productList = purchaseDao.loadProductByPurchaseId(purchaseId);
        if(productList == null || productList.isEmpty()) {
            return null;
        }
        String suppliers = "";
        if(productList != null && productList.size() > 0) {
            suppliers = productList.get(0).getSuppliers();
        }
        //创建临时文件目录
        File dirFile = new File(UUID.randomUUID().toString());
        FileUtils.forceMkdir(dirFile);
        String fileName = dirFile.getAbsolutePath()+ File.separator + UUID.randomUUID().toString() + ".pdf";
        //PDF文件创建开始
        PDFUtil pdfUtil = new PDFUtil();
        Font chapterFont = PDFUtil.createCHineseFont(18, Font.BOLD, new BaseColor(0, 0, 0));//文章标题字体 
        Font sectionFont = PDFUtil.createCHineseFont(14, Font.NORMAL, new BaseColor(0, 0, 0));//文章小节字体 
        Font textFont = PDFUtil.createCHineseFont(12, Font.NORMAL, new BaseColor(0, 0, 0));//小节内容字体 
        pdfUtil.createDocument(fileName);
        
        Chapter chapter = PDFUtil.createChapter("MSF公司采购订单", 1, 1, 0, chapterFont);
        pdfUtil.writeChapterToDoc(chapter);
        
        PdfPTable table = new PdfPTable(6);
        table.setSpacingBefore(15f);//设置表格上面空白宽度
        //table.getDefaultCell().setBorder(1);//设置表格默认为无边框
        table.setTotalWidth(800f);//设置表格的宽度
        PdfPCell cell = null;
        cell = new PdfPCell(new Paragraph("订单号：" + purchase.getOrderNumber(),sectionFont));//建立一个单元格
        cell.setColspan(4);//设置合并单元格的列数
        cell.setBorder(0);
        table.addCell(cell);//增加单元格
        cell = new PdfPCell(new Paragraph("供应商：" + suppliers,sectionFont));//建立一个单元格
        cell.setColspan(2);//设置合并单元格的列数
        cell.setBorder(0);
        table.addCell(cell);//增加单元格
        String[] header = new String[]{"合同号","规格型号","数量","单价","交货期","备注"};
        for (String str : header) {
            cell = new PdfPCell(new Phrase(str,textFont));
            table.addCell(cell);
        }
        float sumPrice = 0f;
        int sumCount = 0;
        for(PurchaseProductBean product : productList) {
            cell = new PdfPCell(new Phrase(product.getContractNumber(),textFont));
            //cell.setBorder(Rectangle.NO_BORDER);
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(product.getPattern(),textFont));
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(String.valueOf(product.getSaleCount()),textFont));
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(product.getSalePrice(),textFont));
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(DateUtil.formateDate(product.getDeliverTime(), DateUtil.DATE_FORMAT),textFont));
            table.addCell(cell);
            cell = new PdfPCell(new Phrase(product.getRemark(),textFont));
            table.addCell(cell);
            sumCount += product.getSaleCount();
            sumPrice += Float.valueOf(product.getTotalPrice());
        }
        cell = new PdfPCell(new Phrase("合计",textFont));
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("",textFont));
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(String.valueOf(sumCount),textFont));
        table.addCell(cell);
        cell = new PdfPCell(new Phrase(String.valueOf(sumPrice),textFont));
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("",textFont));
        table.addCell(cell);
        cell = new PdfPCell(new Phrase("",textFont));
        table.addCell(cell);
        
        cell = new PdfPCell(new Phrase("下达日期："
                + DateUtil.formateDate(purchase.getSaleTime(), DateUtil.DATE_FORMAT), textFont));
        cell.setColspan(6);//设置合并单元格的列数
        cell.setBorder(0);
        table.addCell(cell);
        
        pdfUtil.document.add(table);
        pdfUtil.closeDocument();
        
        return new File(fileName);
    }
    
    /**
     * 生成Excel文件
     * @param purchaseId
     * @return
     * @throws IOException
     */
    public File generateExcel(Integer purchaseId) throws IOException {
        List<PurchaseProductBean> productList = purchaseDao.loadProductByPurchaseId(purchaseId);
        if(productList == null || productList.isEmpty()) {
            return null;
        }
        //这里循环产品列表,汇总产品数量和价格
        int count = 0;
        long price = 0l;
        for (PurchaseProductBean product : productList) {
            count += product.getSaleCount().intValue();
            price += Long.valueOf(product.getTotalPrice());
        }
        PurchaseProductBean p = new PurchaseProductBean();
        p.setContractNumber("汇总");
        p.setSaleCount(count);
        p.setSalePrice(String.valueOf(price));
        productList.add(p);
        
        String[] headers = new String[]{"合同号","规格型号","数量","单价","交货期","备注"};
        //创建临时文件目录
        File dirFile = new File(UUID.randomUUID().toString());
        FileUtils.forceMkdir(dirFile);
        String fileName = dirFile.getAbsolutePath()+ File.separator + UUID.randomUUID().toString() + ".xls";
        ExcelUtil.exportExcel("MSF公司采购订单", headers, productList, fileName);
        return new File(fileName);
    }
    
}
